<template>
	<view class="almost-lottery boxOne">

		<!-- lottery -->
		<view class="almost-lottery__wheel">
			<almost-lottery :lottery-size="lotteryConfig.lotterySize" :action-size="lotteryConfig.actionSize"
				:ring-count="2" :self-rotaty="false" :img-circled="true" :canvasCached="true" :prize-list="prizeList"
				:prize-index="prizeIndex" @reset-index="prizeIndex = -1" @draw-before="handleDrawBefore"
				@draw-start="handleDrawStart" @draw-end="handleDrawEnd" @finish="handleDrawFinish"
				v-if="prizeList.length" :duration='3' :ringCount='10' :selfTime='2500' :lotteryBg="lotteryBg"
				:actionBg="actionBg" :imgDrawed='false' :imgWidth="0" :colors="colors" :strFontColors="strFontColors"
				:strMarginOutside='40' />
		</view>

		<!-- rule -->
		<view class="almost-lottery__rule">
			<view class="freeNumBox cf">
				<view>剩余机会：{{ freeNum }} 次</view>
				<view @click="goList">中奖记录 <u-icon name="arrow-right"></u-icon></view>
			</view>
			<view class="tac f28 fb mt36">
				<text class="f40 mr12"> ·</text>
				机会次数记录
				<text class="f40 ml12"> ·</text>
			</view>
			<view class="csBox">
				<scroll-view scroll-y style="height: 100%;" class="scroll-Y" @scrolltolower="getPrizesLog"
					lower-threshold="100">
					<view class="flex_y_center mt30 overflow_1" v-if="getPrizesLogData.length > 0"
						v-for="(item,key) in getPrizesLogData" :key="key">
						<image v-if="item.puser" class="imgs" :src="$wanlshop.oss(item.puser.avatar)" mode=""></image>
						<view v-if="item.puser" class="ml24 f28 fb c0 flex1 overflow_1">
							{{item.puser.nickname}}
						</view>
						<view v-if="item.puser" class="c3d ml12">
							{{item.createtime_text}}
						</view>
					</view>
					<uni-load-more :status="loadingType" :content-text="contentText" />
				</scroll-view>
			</view>
			<!-- <view class="rule-head">
				<view class="line"></view>
				<text class="title">活动规则</text>
				<view class="line"></view>
			</view>
			<view class="rule-body" v-html="htmlData.content">
			</view> -->
		</view>
		<view class="guizhe" @click="showguizhe = true">
			<image class="guizheimg" src="https://img.aibbyp.com/wechatUser/gz.png" mode=""></image>
		</view>
		<u-modal v-model="showguizhe" :show-title='false' :mask-close-able='true' v-if="showguizhe"
			@click="showguizhe = false" :show-confirm-button='false'>
			<view class="pl20 pr20 pt20 pb20">
				<view class="tac fb f18 ">
					活动规则
				</view>
				<view class="rule-body mt12" v-html="htmlData.content">
				</view>
			</view>
		</u-modal>
		<u-mask :show="maskTrue" v-if="maskTrue" @click="maskTrue = false">
			<view class="warp" v-if="prizeList[myPrizeIndex].type == 1">
				<image class="zjImg" src="https://img.aibbyp.com/wechatUser/luckDraw/zj.png" mode=""></image>
				<view class="f24 cf">
					可在【中奖记录】中查看
				</view>
				<view class="mony">
					{{prizeList[myPrizeIndex].prizeName}}
				</view>
				<view class="mony1" v-if='prizeList[myPrizeIndex].encourage == 1'>
					{{prizeList[myPrizeIndex].price}}
				</view>
			</view>
			<view class="warp " v-else>
				<image class="wzjImg" src="https://img.aibbyp.com/wechatUser/luckDraw/wzj.png" mode=""></image>
				<view class="iconClose" @click="btnfb">
					<u-icon name="close" color="#fff" size="52"></u-icon>
				</view>
			</view>
		</u-mask>
	</view>
</template>

<script>
	import AlmostLottery from '@/uni_modules/almost-lottery/components/almost-lottery/almost-lottery.vue'
	import {
		clearCacheFile,
		clearStore
	} from '@/uni_modules/almost-lottery/utils/almost-utils.js'
	export default {
		name: 'Home',
		components: {
			AlmostLottery
		},
		data() {
			return {
				loadingType: 'loading',
				contentText: {
					contentdown: '',
					contentrefresh: '疯狂加载中...',
					contentnomore: '没有更多数据了'
				},
				page: 1,
				getPrizesLogData: [],
				showguizhe: false,
				maskTrue: false,
				// 开启调试模式
				isDev: true,

				// 以下是转盘配置相关数据
				lotteryConfig: {
					// 抽奖转盘的整体尺寸，单位rpx
					lotterySize: 600,
					// 抽奖按钮的尺寸，单位rpx
					actionSize: 180
				},

				// 以下是转盘 UI 配置
				// 转盘外环图，如有需要，请参考替换为自己的设计稿
				// lotteryBg: require('@/static/lottery-bg.png'),
				colors: ['#FBE2A6', '#FFCB94', '#FA6553', '#fbe877', '#ffa38c', '#FA6553', '#FBE2A6', '#FFCB94',
					'#FA6553', '#fbe877', '#ffa38c', '#FA6553', '#FBE2A6', '#FFCB94', '#FA6553',
					'#fbe877', '#ffa38c', '#FA6553'
				],
				strFontColors: ['#ffffff'],
				lotteryBg: 'https://img.aibbyp.com/wechatUser/luckDraw/yuan.png',
				// 抽奖按钮图
				// actionBg: require('@/static/action-bg.png'),
				actionBg: 'https://img.aibbyp.com/wechatUser/luckDraw/zz.png',

				// 以下是奖品配置数据
				// 奖品数据
				prizeList: [],
				// 奖品是否设有库存
				onStock: true,
				// 中奖下标
				prizeIndex: -1,

				// 是否正在抽奖中，避免重复触发
				prizeing: false,

				// 以下为中奖概率有关数据
				// 是否由前端控制概率，默认不开启，强烈建议由后端控制
				onFrontend: false,
				// 权重随机数的最大值
				prizeWeightMax: 0,
				// 权重数组
				prizeWeightArr: [],

				// 以下为业务需求有关示例数据
				// 金币余额
				goldCoin: 20,
				// 当日免费抽奖次数余额
				freeNum: 0,
				// 每次消耗的金币数
				goldNum: 20,
				// 每天免费抽奖次数
				freeNumDay: 1,
				user_prizes_id: '',
				myPrizeIndex: -1,
				timer: false,
				htmlData: '',
			}
		},
		computed: {
			isApple() {
				return uni.getSystemInfoSync().platform === 'ios'
			}
		},
		async onLoad() {
			this.prizeList = []
			await this.getUserPrizesNumber()
			await this.getPrizeList()

			if (uni.getStorageSync('prize')) {
				this.getPrizesCode()
			}
			await this.getHtml()
			this.getPrizesLog()
			if (option.invitation_code) { //分享进入 -- 获取积分 ========
				uni.setStorage({
					key: 'invitation_code',
					data: option.invitation_code,
				});
			}
		},
		onUnload() {
			uni.hideLoading()
		},
		// 添加分享钩子
		onShareAppMessage() {
			return {
				title:'抽奖大转盘',
				path: `/pages/luckDraw/luckDraw?invitation_code=${uni.getStorageSync('wanlshop:user').uuid || ''}`,
				success: (res) => {},
				fail: (err) => {}
			};
		},
		methods: {

			getPrizesLog() {
				this.$api.get({
					url: '/prizes/getPrizesLog',
					data: {
						page: this.page,
						limit: 15,
					},
					success: res => {
						console.log(res);
						if (this.loadingType == 'noMore') {
							return
						}
						if (res.last_page === res.current_page) {
							this.loadingType = 'noMore';
						} else {
							this.loadingType = 'more';
							this.page++;
						}
						this.getPrizesLogData = this.getPrizesLogData.concat(res.data)
					}
				})
			},
			getHtml() {
				this.$api.get({
					url: '/wanlshop/article/details?id=11',
					success: res => {
						this.htmlData = res
					}
				})
			},
			goList() {
				uni.navigateTo({
					url: '/pages/luckDraw/list'
				})
			},
			btnfb() {
				this.maskTrue = false
				this.myPrizeIndex = -1
			},
			btntx() {
				this.$api.post({
					url: '/prizes/receivePrize',
					data: {
						id: this.user_prizes_id
					}
				}).then(res => {
					console.log(res, 'res');
					if (res) {

					}
				})

			},
			getUserPrizesNumber() {
				this.$api.get({
					url: '/prizes/getUserPrizesNumber'
				}).then(res => {
					console.log(res);
					this.freeNum = res
				})
			},


			getPrizesCode() { // 获取抽奖次数
				this.$api.post({
					url: '/prizes/getPrizesCode',
					data: {
						prizes: uni.getStorageSync('prize')
						// prizes: 'WwrbhSANuPZLTFx98peXq3Vg'

					}
				}).then(res => {
					uni.removeStorage({
						key: 'prize',
						success: function(a) {
							console.log('success');
						}
					});
					this.freeNum = res
				})
			},
			// 重新生成
			handleInitCanvas() {
				clearCacheFile()
				clearStore()

				this.prizeList = []
				this.getPrizeList()
			},
			// 通过 popup 打开
			handleCheckPopup() {
				uni.navigateTo({
					url: '/pages/popup/popup'
				})
			},
			// 获取奖品列表
			async getPrizeList() {
				uni.showLoading({
					title: '奖品准备中...'
				})

				// 等待接口返回的数据进一步处理
				let res = await this.requestApiGetPrizeList()
				console.log('获取奖品列表', res)

				if (res.ok) {
					let data = res.data
					if (data.length) {
						this.prizeList = data
						console.log('已获取到奖品列表数据，开始绘制抽奖转盘')

						// 计算开始绘制的时间
						if (console.time) {
							console.time('绘制转盘用时')
						}

						// 如果开启了前端控制概率
						// 得出权重的最大值并生成权重数组
						if (this.onFrontend) {
							// 生成权重数组并排序取得最大值
							this.prizeWeightArr = this.prizeList.map(item => item.prizeWeight)
							let prizeWeightArrSort = [...this.prizeWeightArr]
							prizeWeightArrSort.sort((a, b) => b - a)

							// 开放自定义权重最大值，没有自定义则取权重数组中的最大值
							this.prizeWeightMax = this.prizeWeightMax > 0 ? this.prizeWeightMax : prizeWeightArrSort[0]
						}
					}
				} else {
					uni.hideLoading()
					uni.showToast({
						title: '获取奖品失败',
						mask: true,
						icon: 'none'
					})
				}
			},
			// 模拟请求 获取奖品列表 接口，
			// 注意这里返回的是一个 Promise
			// 大哥，这里只是模拟，别告诉我你不会对接自己的接口
			requestApiGetPrizeList() {
				return new Promise((resolve, reject) => {
					let requestTimer = setTimeout(() => {
						clearTimeout(requestTimer)
						requestTimer = null

						this.$api.post({
							url: '/prizes/getPrizesList',
							data: {}
						}).then(res => {

							res.forEach(a => {
								a.prizeImage = this.$wanlshop.oss(a.prizeImage)
								a.prizeId = a.id
							})

							resolve({
								ok: true,
								data: res
							})

						})
						// prizeStock 奖品库存
						// prizeWeight 中奖概率，数值越大中奖概率越高，权重一样时随机中奖

					}, 200)
				})
			},
			// 抽奖开始之前
			handleDrawBefore(callback) {
				console.log('抽奖开始之前')
				let flag = false

				// 还有免费数次或者剩余金币足够抽一次
				if (this.freeNum > 0) {
					// 更新免费次数或金币余额

					flag = true
				} else {
					flag = false
					uni.showModal({
						title: '抽奖次数已用完',
						content: '下单获取更多次数？',
						success: (res) => {
							// 这里需要根据业务需求处理，一般情况下会引导用户前往赚取金币的页面
							uni.navigateBack({
								delta: 1
							})
						}
					})
				}

				callback(flag)
			},
			// 本次抽奖开始
			handleDrawStart() {
				console.log('触发抽奖按钮')
				if (this.timer == false) {
					this.tryLotteryDraw()
					this.timer = true
					setTimeout(() => {
						this.timer = false
					}, 500)
				}
			},
			// 尝试发起抽奖
			tryLotteryDraw() {
				console.log('旋转开始，获取中奖下标......')
				// 判断是否由前端控制概率
				this.remoteGetPrizeIndex()

			},
			// 本地获取中奖下标
			localGetPrizeIndex() {
				console.warn('###当前处于前端控制中奖概率，安全起见，强烈建议由后端控制###')
				// 前端控制概率的情况下，需要拿到最接近随机权重且大于随机权重的值
				// 后端控制概率的情况下，通常会直接返回 prizeId
				if (!this.prizeWeightMax || !this.prizeWeightArr.length) {
					console.warn('###当前已开启前端控制中奖概率，但是奖品数据列表中的 prizeWeight 参数似乎配置不正确###')
					return
				}
				console.log('当前权重最大值为 =>', this.prizeWeightMax)

				// 注意这里使用了 Math.ceil，如果某个权重的值为 0，则始终无法中奖
				let randomWeight = Math.ceil(Math.random() * this.prizeWeightMax)
				console.log('本次权重随机数 =>', randomWeight)

				// 生成大于等于随机权重的数组
				let tempMaxArrs = []
				this.prizeList.forEach((item) => {
					if (item.prizeWeight >= randomWeight) {
						tempMaxArrs.push(item.prizeWeight)
					}
				})
				console.log('tempMaxArrs', tempMaxArrs)

				// 如果大于随机权重的数组有值，先对这个数组排序然后取值
				// 反之新建一个临时的包含所有权重的已排序数组，然后取值
				let tempMaxArrsLen = tempMaxArrs.length
				if (tempMaxArrsLen) {
					tempMaxArrs.sort((a, b) => a - b)
					// 取值时，如果存在多个值，分两种情况
					if (tempMaxArrsLen > 1) {
						// 检查是否存在重复的值
						let sameCount = 0
						for (let i = 0; i < tempMaxArrs.length; i++) {
							if (tempMaxArrs[i] === tempMaxArrs[0]) {
								sameCount++
							}
						}

						// 值不相等的情况下取最接近的值，也就是第1个值
						if (sameCount === 1) {
							this.prizeIndex = this.prizeWeightArr.indexOf(tempMaxArrs[0])
						} else {
							// 存在值相等时，随机取值，当然这里你可以自己决定是否随机取值
							let sameWeight = tempMaxArrs[0]
							let sameWeightArr = []
							let sameWeightItem = {}
							this.prizeWeightArr.forEach((item, index) => {
								if (item === sameWeight) {
									sameWeightArr.push({
										prizeWeight: item,
										index
									})
								}
							})
							console.log('sameWeightArr', sameWeightArr)
							sameWeightItem = sameWeightArr[Math.floor(Math.random() * sameWeightArr.length)]
							console.log('sameWeightItem', sameWeightItem)
							this.prizeIndex = sameWeightItem.index
						}
					} else {
						this.prizeIndex = this.prizeWeightArr.indexOf(tempMaxArrs[0])
					}
				}

				console.log('本次抽中奖品 =>', this.prizeList[this.prizeIndex].prizeName)

				// 如果奖品设有库存
				if (this.onStock) {
					console.log('本次奖品库存 =>', this.prizeList[this.prizeIndex].prizeStock)
				}
			},
			// 远程请求接口获取中奖下标
			// 大哥，这里只是模拟，别告诉我你不会对接自己的接口
			remoteGetPrizeIndex() {
				console.warn('###当前处于模拟的请求接口，并返回了中奖信息###')
				this.$api.post({
					url: '/prizes/prizeDraw'
				}).then(res => {
					let _this = this
					this.user_prizes_id = res.user_prizes_id

					for (let i in _this.prizeList) {
						if (_this.prizeList[i].prizeId == res.prize_id) {
							_this.prizeIndex = Number(i)
							_this.myPrizeIndex = Number(i)
							_this.prizeList[Number(i)].price = res.price
							console.log('本次抽中奖品 =>11', _this.prizeList[_this.prizeIndex])
							this.getUserPrizesNumber()

						}
					}
				})
				return
				// 模拟请求接口获取中奖信息

				let stoTimer = setTimeout(() => {
					stoTimer = null
					let list = [..._this.prizeList]
					// 这里随机产生的 prizeId 是模拟后端返回的 prizeId
					let prizeId = Math.floor(Math.random() * list.length + 1)
					// 拿到后端返回的 prizeId 后，开始循环比对得出那个中奖的数据
					for (let i = 0; i < list.length; i++) {
						let item = list[i]
						if (item.prizeId === prizeId) {
							// 中奖下标
							_this.prizeIndex = i
							_this.myPrizeIndex = i
							break
						}
					}
					console.log('本次抽中奖品 =>', _this.prizeList[_this.prizeIndex].prizeName)
					// 如果奖品设有库存
					if (_this.onStock) {
						console.log('本次奖品库存 =>', _this.prizeList[_this.prizeIndex].prizeStock)
					}
				}, 200)
			},
			// 本次抽奖结束
			handleDrawEnd() {
				console.log('旋转结束，执行拿到结果后到逻辑', this.prizeList, this.myPrizeIndex)
				// 旋转结束后，开始处理拿到结果后的逻辑
				if (this.prizeList[this.myPrizeIndex].type == 1) {
					this.btntx()
				}
				this.timer = false
				this.maskTrue = true

			},
			// 抽奖转盘绘制完成
			handleDrawFinish(res) {
				console.log('抽奖转盘绘制完成', res)
				if (res.ok) {
					// 计算结束绘制的时间
					if (console.timeEnd) {
						console.timeEnd('绘制转盘用时')
					}
				}

				let stoTimer = setTimeout(() => {
					stoTimer = null

					uni.hideLoading()
					uni.showToast({
						title: res.msg,
						mask: true,
						icon: 'none'
					})
				}, 50)
			}
		},

	}
</script>

<style lang="scss" scoped>
	.guizhe {
		position: fixed;
		right: 0;
		top: 200rpx;

		.guizheimg {
			width: 86rpx;
			height: 48rpx;
		}

	}

	.csBox {
		max-height: 80vh;
		margin-top: 24rpx;
		min-height: 300rpx;
		padding: 30rpx 48rpx 48rpx 48rpx;
		background: #FFFFFF;
		border-radius: 20rpx 20rpx 20rpx 20rpx;
		overflow: scroll;

		.imgs {
			width: 90rpx;
			height: 90rpx;
			border-radius: 50%;
		}
	}

	.freeNumBox {
		margin-top: 100rpx;
		display: flex;
		justify-content: space-between;
	}

	::v-deep .almost-lottery__canvas-img {
		width: 470rpx !important;
		height: 470rpx !important;
		left: 66rpx !important;
		top: 66rpx !important;
	}

	.warp {
		width: 100%;
		height: 100vh;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;

		.zjImg {
			width: 434rpx;
			height: 470rpx;
		}

		.wzjImg {
			width: 434rpx;
			height: 438rpx;
		}

		.iconClose {
			margin-top: 48rpx;
			width: 80rpx;
			height: 80rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			border: 4rpx solid #fff;
			border-radius: 50% 50%;
		}

		.mony {
			position: relative;
			font-size: 48rpx;
			top: -466rpx;
			color: #E81D2B;
		}

		.mony1 {
			position: relative;
			font-size: 24rpx;
			top: -456rpx;
			color: #E81D2B;
			font-weight: bold;
		}

		.txBtn {
			font-weight: 500;
			font-size: 32rpx;
			padding: 14rpx 56rpx;
			font-family: Alimama ShuHeiTi, Alimama ShuHeiTi;
			color: #FFFFFF;
			background: linear-gradient(95deg, #F66047 0%, #E10711 100%);
			border-radius: 40rpx 40rpx 40rpx 40rpx;
		}
	}

	.almost-lottery {

		flex: 1;

	}

	.boxOne {
		background: url('https://img.aibbyp.com/wechatUser/luckDraw/bac.png') no-repeat center/cover;
		padding-top: 440rpx;
		height: 100vh;
		background-repeat: no-repeat;
		background-size: 100% auto;
		padding-bottom: 30rpx;
	}


	.almost-lottery__head {
		position: relative;
		width: 100%;
		height: 640rpx;


		.action {
			position: relative;
			top: 400rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			width: 480rpx;
			height: 88rpx;
			line-height: 88rpx;
			margin: 0 auto;
			color: #FFFFFF;
			font-size: 32rpx;
			background-color: rgba(255, 136, 61, 1);
			border-radius: 44rpx;
		}

		.action-shadow {
			box-shadow: 0px 14rpx 0px 0px rgba(235, 112, 36, 1);
		}

		.gold {
			width: 44rpx;
			height: 44rpx;
			margin-right: 10rpx;
			background-repeat: no-repeat;
			background-position: center center;
			background-size: contain;
			background-image: url("https://img.aibbyp.com/wechatUser/lottery/gold.png");

			@media (-webkit-min-device-pixel-ratio: 2),
			(min-device-pixel-ratio: 2) {
				background-image: url("https://img.aibbyp.com/wechatUser/lottery/gold@2x.png");
			}

			@media (-webkit-min-device-pixel-ratio: 3),
			(min-device-pixel-ratio: 3) {
				background-image: url("https://img.aibbyp.com/wechatUser/lottery/gold@3x.png");
			}
		}

		.num {
			color: #F9FC31;
		}

		.tip {
			position: relative;
			top: 428rpx;
			color: #FFFFFF;
			font-size: 24rpx;
			text-align: center;
		}
	}

	.almost-lottery__wheel {
		text-align: center;

		.almost-lottery__count {
			display: flex;
			flex-direction: column;
			justify-content: space-between;
			align-items: center;
			text-align: center;
			padding: 40rpx 0;
		}

		.text {
			color: #FFFFFF;
			font-size: 24rpx;
		}
	}

	.almost-lottery__rule {
		padding: 20rpx 28rpx;
		color: #FFF8CB;

		.rule-head {
			display: flex;
			justify-content: space-around;
			align-items: center;
			margin: 40rpx 0;

			.line {
				flex: 1;
				height: 1px;
				background-color: #FFF3A5;
			}

			.title {
				width: 280rpx;
				color: #F63857;
				line-height: 70rpx;
				text-align: center;
				margin: 0 20rpx;
				border-radius: 8rpx;
				background-image: linear-gradient(0deg, rgba(255, 242, 158, 1), rgba(255, 244, 168, 1));
			}
		}

		.rule-body {
			color: #FFF8CB;
			font-size: 24rpx;
			padding: 10rpx 0 40rpx;

			.item {
				display: flex;

				margin-bottom: 10rpx;
			}

			.number {
				position: relative;
				top: 10rpx;
				width: 28rpx;
				height: 28rpx;
				line-height: 28rpx;
				text-align: center;
				color: #F63857;
				background: #FFF8CB;
				border-radius: 50%;
				margin-right: 10rpx;
			}

			.text {
				flex: 1;
			}

			.item-rule .text {
				display: flex;
				flex-direction: column;
			}
		}
	}

	.almost-lottery__action-dev {
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
		width: 400rpx;
		height: 80rpx;
		border-radius: 10rpx;
		text-align: center;
		background-color: red;
		margin: 0 auto 40rpx;

		.text {
			color: #FFFFFF;
			font-size: 28rpx;
		}
	}

	.almost-lottery__popup-wrap {
		flex: 1;
		display: flex;
		justify-content: center;
		align-items: center;

		.almost-lottery {
			background: transparent;
		}
	}
</style>